package com.esender.strategy.filter.impl;

import com.esender.common.constant.CacheConstant;
import com.esender.common.enums.ExceptionEnums;
import com.esender.common.exception.StrategyException;
import com.esender.common.model.StandardSubmit;
import com.esender.strategy.client.BeaconCacheClient;
import com.esender.strategy.filter.StrategyFilter;
import com.esender.strategy.util.ClientBalanceUtil;
import com.esender.strategy.util.ErrorSendMsgUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

/**
 * 扣费策略过滤器
 */
@Service(value = "fee")
@Slf4j
public class FeeStrategyFilter implements StrategyFilter {
    @Autowired
    private BeaconCacheClient beaconCacheClient;
    @Autowired
    private ErrorSendMsgUtil errorSendMsgUtil;
    private final String BALANCE = "balance";
    @Override
    public void strategy(StandardSubmit standardSubmit) {
        log.info("【策略模块-扣费校验】   校验ing…………");
        //1、获取submit中封装的金额
        Long fee = standardSubmit.getFee();
        Long clientId = standardSubmit.getClientId();
        // 调用redis的decr扣减预扣的金额
        Long amount = beaconCacheClient.hIncrBy(CacheConstant.CLIENT_BALANCE + clientId, BALANCE, -fee);

        // 判断预扣后的剩下的金额是否超过最大金额限制
        Long clientAmountLimit = ClientBalanceUtil.getClientAmountLimit(clientId);
        if (amount < clientAmountLimit){
            log.info("【策略模块-扣费校验】   扣除费用后，超过欠费余额的限制，无法发送短信！！");
            //5、如果超过了，需要将扣除的费用增加回去，并且做后续处理
            beaconCacheClient.hIncrBy(CacheConstant.CLIENT_BALANCE + clientId, BALANCE, fee);
            standardSubmit.setErrorMsg(ExceptionEnums.BALANCE_NOT_ENOUGH.getMsg() + "mobile = " + standardSubmit.getMobile());
            errorSendMsgUtil.sendWriteLog(standardSubmit);
            // 推送报告
            errorSendMsgUtil.sendPushReport(standardSubmit);
            throw new StrategyException(ExceptionEnums.BALANCE_NOT_ENOUGH);
        }
        log.info("【策略模块-扣费校验】   扣费成功！！");
    }
}
